package com.longteng.lesson.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by Administrator
 * DATE : 2018/5/22
 * TIME : 22:43
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Controller
public class FileController {

    @RequestMapping("/filePage")
    public String filePage(){
        return "uploadPage/uploadfile";
    }


    @RequestMapping(value = "/testDownload", method = RequestMethod.GET)
    public void testDownload(HttpServletResponse res,String type) {
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:dataFile/aa.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        attachment
        //如果是什么类型的文件走inline
        //如果是什么类型的文件走attachment
        res.setHeader("Content-Disposition", type+";filename=" + file.getName());
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }

    @RequestMapping("/uploadFile")
    public ModelAndView updateFile(@RequestParam(value = "file") MultipartFile myfiles) {
        try {
            File file = null;
            try {
                file = ResourceUtils.getFile("dataFile");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File file1=new File("d:"+File.separator+myfiles.getOriginalFilename());
            myfiles.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
